<?php

namespace Viettrans\FrontBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

/**
 * Ajax controller.
 * 
 * @Route("/ajax")
 */
class AjaxController extends Controller {
    /**
     * @Route("/locality/", name="ajax_get_localities")
     */
    public function getLocalitiesAction() {
        $input = trim($this->getRequest()->query->get('query'));
        
        $myCacheManager = $this->get('my_cache_manager');
        
        $data = $myCacheManager->getLocalities(array('input'=>$input));

        return new Response($data, '200', array());
    }
    
    /**
     * @Route("/contact_poster/", name="ajax_contact_poster")
     */
    public function contactPosterAction() {
        # Get captcha value from session
        $captcha = $this->get('session')->get('captcha');

        # Get the post variables
        $request = $this->getRequest();
        $clientName = $request->request->get('clientName');
        $clientEmail = $request->request->get('clientEmail');
        $clientTelephone = $request->request->get('clientTelephone');
        $clientMessage = $request->request->get('clientMessage');
        $clientCaptcha = $request->request->get('clientCaptcha');
        
        # Check the info
        $formErrors = array();
        $isFormValid = true;
        $myFormValidator = $this->get('my_form_validator');
        
        # Check client name
        if ($myFormValidator->isTextValid($clientName, 20)) {
            $formErrors['clientNameError'] = false;
        } else {
            $formErrors['clientNameError'] = true;
            $isFormValid = false;
        }
        
        # Check message
        if ($myFormValidator->isTextValid($clientName, 500)) {
            $formErrors['clientMessageError'] = false;
        } else {
            $formErrors['clientMessageError'] = true;
            $isFormValid = false;
        }
        
        # Check email
        if ($myFormValidator->isEmailValid($clientEmail)) {
            $formErrors['clientEmailError'] = false;
        } else {
            $formErrors['clientEmailError'] = true;
            $isFormValid = false;
        }
        
        # Check telephone
        if ($myFormValidator->isTelephoneValid($clientTelephone, false)) {
            $formErrors['clientTelephoneError'] = false;
        } else {
            $formErrors['clientTelephoneError'] = true;
            $isFormValid = false;
        }
        
        # Check captcha
        if ($captcha == $clientCaptcha) {
            $formErrors['clientCaptchaError'] = false;
        } else {
            $formErrors['clientCaptchaError'] = true;
            $isFormValid = false;
        }
        
        # If there is no error then send contact email
        if ($isFormValid) {
            $announcement = $this->getDoctrine()
                                 ->getEntityManager()
                                 ->getRepository('ViettransFrontBundle:Announcement')
                                 ->find($request->request->get('announcementId'));

            $message = \Swift_Message::newInstance()
                ->setSubject('Viettrans - Bạn có tin nhắn liên hệ từ Viettrans.net')
				->setFrom(array(
					'no-reply@viettrans.net' => 'Viettrans'
				))
				->setReplyTo('no-reply@viettrans.net')
                ->setTo(array(
					$announcement->getContactEmail() => $announcement->getContactName()
				))
                ->setBody($this->renderView('ViettransFrontBundle:Email:contactPoster.html.twig', array(
                	'contactName'     => $announcement->getContactName(),
                    'title'           => $announcement->getTitle(),
                    'clientName'      => $clientName,
                    'clientEmail'     => $clientEmail,
                    'clientTelephone' => $clientTelephone,
                	'clientMessage'   => $clientMessage,
                )), 'text/html', 'utf-8');

            $formErrors['sendEmailError'] = (!$this->get('mailer')->send($message)) ? true : false;
        }
        
        return new Response(json_encode($formErrors), '200', array());
    }
}
